package com.itcast.gateway.service.impl;

import com.itcast.gateway.service.DynamicRouteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

/**
 * @author zheng.zhang
 * Description 动态路由刷新
 * @date 2020/9/10 17:23
 * Version 1.0
 */
@Slf4j
@Service
public class DynamicRouteServiceImpl implements DynamicRouteService {
    @Autowired
    private RouteDefinitionWriter routeDefinitionWriter;

    private ApplicationEventPublisher publisher;

    @Override
    public void setApplicationEventPublisher(@NonNull ApplicationEventPublisher applicationEventPublisher) {
        this.publisher = applicationEventPublisher;
    }

    @Override
    public boolean addRoute(RouteDefinition routeDefinition) {
        boolean flag = false;
        try {
            // 一定添加subscribe()，要不然不会执行添加
            routeDefinitionWriter.save(Mono.just(routeDefinition)).subscribe();
            // 刷新路由
            this.publisher.publishEvent(new RefreshRoutesEvent(this));
            flag = true;
        } catch (Exception e) {
            log.error("添加路由出错： {}", e.getMessage());
        }
        return flag;
    }

    @Override
    public boolean updateRoute(RouteDefinition definition) {
        boolean flag = false;
        try {
            // 1、删除原路由
            routeDefinitionWriter.delete(Mono.just(definition.getId()));
            // 2、保存新路由
            routeDefinitionWriter.save(Mono.just(definition)).subscribe();
            // 3、刷新路由
            this.publisher.publishEvent(new RefreshRoutesEvent(this));
            flag = true;
        } catch (Exception e) {
            log.error("更新路由失败，路由ID： {}，异常信息为： {}", definition.getId(), e.getMessage());
        }
        return flag;
    }

    @Override
    public boolean deleteRoute(String id) {
        boolean flag = false;
        try {
            // 删除路由
            routeDefinitionWriter.delete(Mono.just(id));
            // 刷新路由
            this.publisher.publishEvent(new RefreshRoutesEvent(this));
            flag = true;
        } catch (Exception e) {
            log.error("删除失败： {}", e.getMessage());
        }
        return flag;
    }

    @Override
    public boolean refreshRoute() {
        boolean flag = false;
        try {
            this.publisher.publishEvent(new RefreshRoutesEvent(this));
            flag = true;
        } catch (Exception e) {
            log.error("刷新失败：{}", e.getMessage());
        }
        return flag;
    }
}
